<?php

namespace Biz\service\wiki;

use Biz\cache\wiki\WikiBuyCache;
use Biz\model\wiki\WikiBuyModel;
use Doraemon\cache\UserCounter;

class WikiBuyService
{
    /**
     * 商品买过 6.0 新增
     * @param $uid
     * @param $wikiId
     * @return bool
     * @throws \Exception
     */
    public static function wikiBuy($uid, $wikiId)
    {
        $data = [
            'uid' => $uid,
            'wiki_id' => $wikiId,
            'status' => WikiBuyModel::STATUS_NORMAL,
        ];

        $status = WikiBuyModel::getStatus($uid, $wikiId);
        if ($status == 0) { //数据不存在 执行插入操作
            $insertId = WikiBuyModel::insertData($data);
            if (!$insertId) {
                throw new \Exception('添加失败');
            }
        } else {//数据已存在 执行更新操作
            if (WikiBuyModel::STATUS_NORMAL == $status) {
                throw new \Exception('您已添加到「买过清单」，请勿重复操作');
            }
            $upCount = WikiBuyModel::updateData($data, ['uid' => $uid, 'wiki_id' => $wikiId]);
            if ($upCount == 0) {
                throw new \Exception('添加失败');
            }
        }
        //更新计数器缓存

        // 用户买过商品数累加
        UserCounter::increaseUserCounter($uid, UserCounter::TYPE_BUY_Wiki);
        //wiki添加买过数
        WikiBuyCache::increaseCounter($wikiId);

        return true;
    }

    /**
     * 商品取消买过 6.0 新增
     * @param $uid
     * @param $wikiId
     * @throws \Exception
     */
    public static function unWikiBuy($uid, $wikiId)
    {
        $data = [
            'uid' => $uid,
            'wiki_id' => $wikiId,
            'status' => WikiBuyModel::STATUS_DEL,
        ];
        // 先查询状态
        $status = WikiBuyModel::getStatus($uid, $wikiId);
        if ($status == 0) {
            throw new \Exception('参数错误');
        }
        if (WikiBuyModel::STATUS_DEL == $status) {
            throw new \Exception('您已经取消买过，请勿重复操作');
        }
        //执行更新操作
        $upCount = WikiBuyModel::updateData($data, ['uid' => $uid, 'wiki_id' => $wikiId]);
        if ($upCount) {
            //更新计数器缓存

            // 用户买过商品数累加
            UserCounter::decreaseUserCounter($uid, UserCounter::TYPE_BUY_Wiki);
            //wiki添加买过数
            WikiBuyCache::decreaseCounter($wikiId);
        }
    }

    /**
     * @param $uid
     * @param $wikiIds
     * @return array
     */
    public static function isBuy($uid,$wikiIds): array
    {
        $where=[
          'uid'=>$uid,
          'wiki_id'=>$wikiIds,
          'status'=>WikiBuyModel::STATUS_NORMAL
        ];
        $list = WikiBuyModel::selectByWhere($where,['wiki_id','status']);
        return array_column($list,'status','wiki_id');

    }

}
